// 获取canvas和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 小鸟属性
let bird = {
    x: 100,
    y: 300,
    radius: 20,
    velocityX: 2,  // 水平速度
    velocityY: 0,
    gravity: 0.5,
    jumpStrength: -10
};

// 猪的位置
let pig = {
    x: 700,
    y: 300,
    radius: 30
};

// 障碍物
let obstacles = [
    { x: 400, y: 200, width: 20, height: 200 },
    { x: 600, y: 300, width: 20, height: 150 },
    { x: 800, y: 150, width: 20, height: 100 },  // 新增障碍物
    { x: 1000, y: 250, width: 20, height: 120 } // 新增障碍物
];

// 键盘控制
document.addEventListener('keydown', function (e) {
    if (e.code === 'Space') {
        bird.velocityY = bird.jumpStrength;
    }
});

// 更新小鸟位置
function updateBird() {
    bird.velocityY += bird.gravity;
    bird.y += bird.velocityY;
    bird.x += bird.velocityX;  // 水平移动

    // 地面碰撞检测
    if (bird.y + bird.radius > canvas.height) {
        bird.y = canvas.height - bird.radius;
        bird.velocityY = 0;
    }

    // 天花板碰撞检测
    if (bird.y - bird.radius < 0) {
        bird.y = bird.radius;
        bird.velocityY = 0;
    }

    // 画布右侧边界处理
    if (bird.x - bird.radius > canvas.width) {
        bird.x = 0 - bird.radius;  // 从左侧重新进入
    }
}

// 检测碰撞
function checkCollision(obj1, obj2) {
    let dx = obj1.x - obj2.x;
    let dy = obj1.y - obj2.y;
    let distance = Math.sqrt(dx * dx + dy * dy);

    return distance < obj1.radius + obj2.radius;
}

// 绘制所有元素
function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制小鸟
    ctx.beginPath();
    ctx.arc(bird.x, bird.y, bird.radius, 0, Math.PI * 2);
    ctx.fillStyle = "yellow";
    ctx.fill();

    // 绘制猪
    ctx.beginPath();
    ctx.arc(pig.x, pig.y, pig.radius, 0, Math.PI * 2);
    ctx.fillStyle = "red";
    ctx.fill();

    // 绘制障碍物
    ctx.fillStyle = "green";
    for (let obs of obstacles) {
        ctx.fillRect(obs.x, obs.y, obs.width, obs.height);
    }
}

// 游戏主循环
function gameLoop() {
    updateBird();
    draw();

    // 检查与猪的碰撞
    if (checkCollision(bird, pig)) {
        alert("击中猪！游戏结束");
        clearInterval(gameInterval);
    }

    // 检查与障碍物的碰撞
    for (let obs of obstacles) {
        if (
            bird.x + bird.radius > obs.x &&
            bird.x - bird.radius < obs.x + obs.width &&
            bird.y + bird.radius > obs.y &&
            bird.y - bird.radius < obs.y + obs.height
        ) {
            alert("撞到障碍物！游戏结束");
            clearInterval(gameInterval);
        }
    }
}

// 启动游戏
let gameInterval = setInterval(gameLoop, 1000 / 60);